package test.marui.com.mytest.view.bDLocation;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresPermission;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Iterator;

import test.marui.com.mytest.R;

/**
 * 测试北斗定位
 * Created by MR on 2019/3/31.
 */
public class BDLocationActivity extends AppCompatActivity implements View.OnClickListener {

    private int PERMISSION_REQUEST_CODE_STORAGE = 1;

    private static final String TAG = "BDLocationActivity";

    private TextView tv_bd_latitude;
    private TextView tv_bd_longitude;
    private TextView tv_bd_altitude;

    private TextView tv_normal_latitude;
    private TextView tv_normal_longitude;
    private TextView tv_normal_altitude;

    private LocationManager lm;

    public ArrayList<String> locationList = new ArrayList<>();

    private long lastMillis;
    private long period = 10000;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bd_location);

        View headView = LayoutInflater.from(this).inflate(R.layout.activity_bd_location_head, null, false);
        tv_bd_latitude = headView.findViewById(R.id.tv_bd_latitude);
        tv_bd_longitude = headView.findViewById(R.id.tv_bd_longitude);
        tv_bd_altitude = headView.findViewById(R.id.tv_bd_altitude);
        TextView tv_get_bd_location = headView.findViewById(R.id.tv_get_bd_location);
        tv_normal_latitude = headView.findViewById(R.id.tv_normal_latitude);
        tv_normal_longitude = headView.findViewById(R.id.tv_normal_longitude);
        tv_normal_altitude = headView.findViewById(R.id.tv_normal_altitude);
        TextView tv_get_normal_location = headView.findViewById(R.id.tv_get_normal_location);

        tv_get_bd_location.setOnClickListener(this);
        tv_get_normal_location.setOnClickListener(this);


        RecyclerView rv = findViewById(R.id.rv);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        rv.setLayoutManager(manager);
        MyAdapter adapter = new MyAdapter(this, locationList, headView);
        rv.setAdapter(adapter);

        //获取定位服务
//        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // 判断GPS是否正常启动
        if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Toast.makeText(this, "请开启GPS导航...", Toast.LENGTH_SHORT).show();
            setLog("请开启GPS导航...");
            // 返回开启GPS导航设置界面
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(intent, 0);
            return;
        }

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        /**
         * 监听状态
         */
        lm.addGpsStatusListener(listener);

        /**
         * 绑定监听，有4个参数 参数1，设备：有GPS_PROVIDER和NETWORK_PROVIDER两种 参数2，位置信息更新周期，单位毫秒
         * 参数3，位置变化最小距离：当位置距离变化超过此值时，将更新位置信息 参数4，监听
         * 备注：参数2和3，如果参数3不为0，则以参数3为准；参数3为0，则通过时间来定时更新；两者为0，则随时刷新。
         * 1秒更新一次，或最小位移变化超过1米更新一次；
         * 注意：此处更新准确度非常低，推荐在service里面启动一个Thread，在run中sleep
         * (10000);然后执行handler.sendMessage(),更新位置
         */

        if (lm.getProvider(LocationManager.GPS_PROVIDER) != null) {
            Log.d("GPS_PROVIDER执行：", "GPS方法执行。。。。。。。。");
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000,
                    0, locationListener);
        } else if (lm.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
            Log.d("NETWORK执行：", "NETWORK方法执行。。。。。。。。");
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                    5000, 0, locationListener);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_get_bd_location:
                startLocation(1);
                tv_bd_latitude.setText(String.valueOf(latitude));
                tv_bd_longitude.setText(String.valueOf(longitude));
                tv_bd_altitude.setText(String.valueOf(altitude));
                locationList.add("北斗\n经度：" + longitude + "\n纬度："
                        + latitude + "\n高程：" + altitude);
                break;
            case R.id.tv_get_normal_location:
                startLocation(2);
                tv_normal_latitude.setText(String.valueOf(latitude));
                tv_normal_longitude.setText(String.valueOf(longitude));
                tv_normal_altitude.setText(String.valueOf(longitude));
                locationList.add("经度：" + longitude + "\n纬度："
                        + latitude + "\n高程：" + altitude);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        lm.removeUpdates(locationListener);
    }

    private void setLog(String txt) {
        setLogInfo(txt);
    }

    private void setLogInfo(String txt) {
//        locationList.add(txt);
    }

    // 状态监听
    GpsStatus.Listener listener = new GpsStatus.Listener() {
        public void onGpsStatusChanged(int event) {
            switch (event) {
                // 第一次定位
                case GpsStatus.GPS_EVENT_FIRST_FIX:
                    Log.i(TAG, "第一次定位");
                    setLog("第一次定位");
                    break;
                // 卫星状态改变
                case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                    long currenMillis = System.currentTimeMillis();// 当前时间
                    if ((currenMillis - lastMillis) > period) {
                        lastMillis = currenMillis;
                        // 获取当前状态
                        if (ActivityCompat.checkSelfPermission(BDLocationActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            return;
                        }
                        GpsStatus gpsStatus = lm.getGpsStatus(null);
                        // 获取卫星颗数的默认最大值
                        int maxSatellites = gpsStatus.getMaxSatellites();
                        // 创建一个迭代器保存所有卫星
                        Iterator<GpsSatellite> iters = gpsStatus.getSatellites()
                                .iterator();
                        int count = 0;
                        while (iters.hasNext() && count <= maxSatellites) {
                            count++;
                        }
                        Log.i(TAG, "卫星状态改变,搜索到：" + count + "颗卫星");
                        setLog("卫星状态改变,搜索到：" + count + "颗卫星 \n经度：" );
                    }
                    break;
                // 定位启动
                case GpsStatus.GPS_EVENT_STARTED:
                    Log.i(TAG, "定位启动");
                    setLog("定位启动");
                    break;
                // 定位结束
                case GpsStatus.GPS_EVENT_STOPPED:
                    Log.i(TAG, "定位结束");
                    setLog("定位结束");
                    break;
            }
        }
    };

    private double longitude;
    private double latitude;
    private double altitude;
    // 位置监听
    private LocationListener locationListener = new LocationListener() {

        /**
         * 位置信息变化时触发
         */
        public void onLocationChanged(Location location) {
            setLog("经度：" + location.getLongitude() + "\n纬度："
                    + location.getLatitude() + "\n高程：" + location.getAltitude());
            longitude = location.getLongitude();
            latitude = location.getLatitude();
            altitude = location.getAltitude();

        }

        /**
         * GPS状态变化时触发
         */
        public void onStatusChanged(String provider, int status, Bundle extras) {
            switch (status) {
                // GPS状态为可见时
                case LocationProvider.AVAILABLE:
                    Log.i(TAG, "当前GPS状态为可见状态");

                    setLog("当前GPS状态为可见状态");
                    break;
                // GPS状态为服务区外时
                case LocationProvider.OUT_OF_SERVICE:
                    Log.i(TAG, "当前GPS状态为服务区外状态");
                    setLog("当前GPS状态为服务区外状态");
                    break;
                // GPS状态为暂停服务时
                case LocationProvider.TEMPORARILY_UNAVAILABLE:
                    Log.i(TAG, "当前GPS状态为暂停服务状态");
                    setLog("当前GPS状态为暂停服务状态");
                    break;
            }
        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }

    };


    private void startLocation(int type) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            requestPermission();
            return;
        }

        // 为获取地理位置信息时设置查询条件 是按GPS定位还是network定位
        Location location = null;
        location = getLastKnownLocation();
        if (location == null) {
            return;
        }

        if (type == 1) {
            tv_bd_latitude.setText(String.valueOf(location.getLatitude()));
            tv_bd_longitude.setText(String.valueOf(location.getLongitude()));
            tv_bd_altitude.setText(String.valueOf(location.getAltitude()));
        } else if (type == 2) {
            tv_normal_latitude.setText(String.valueOf(location.getLatitude()));
            tv_normal_longitude.setText(String.valueOf(location.getLongitude()));
            tv_normal_altitude.setText(String.valueOf(location.getAltitude()));
        }

    }

    @RequiresPermission(anyOf = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    @SuppressLint("MissingPermission")
    protected Location getLastKnownLocation() {
        Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location != null) {
            return location;
        }
        location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if (location != null) {
            return location;
        }

        location = lm.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
        return location;
    }

    /**
     * 6.0动态申请权限
     */
    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_CODE_STORAGE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (PERMISSION_REQUEST_CODE_STORAGE == requestCode) {
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(BDLocationActivity.this, "没有开启定位权限", Toast.LENGTH_SHORT).show();
                // 转到手机设置界面，用户设置GPS
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                int START_ACTION_LOCATION_SOURCE_SETTINGS = 2;
                startActivityForResult(intent, START_ACTION_LOCATION_SOURCE_SETTINGS); // 设置完成后返回到原来的界面
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private Context context;
        private ArrayList<String> list;
        private int TYPE_HEADER = 1001;
        private View headerView;

        MyAdapter(Context context, ArrayList<String> list, View headerView) {
            this.context = context;
            this.list = list;
            this.headerView = headerView;
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView title;

            ViewHolder(View v) {
                super(v);
                title = v.findViewById(R.id.textView);
            }
        }

        /**
         * 头布局的viewholder
         */
        class HeaderViewHolder extends RecyclerView.ViewHolder {
            HeaderViewHolder(View itemView) {
                super(itemView);
            }
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            if (viewType==TYPE_HEADER){
                return new HeaderViewHolder(headerView);
            }
            View view = LayoutInflater.from(context).inflate(R.layout.item_main, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

            if (holder instanceof ViewHolder){
                ((ViewHolder) holder).title.setText(list.get(position-1));
            }
        }

        @Override
        public int getItemCount() {
            if (list == null) {
                return 1;
            }
            return list.size()+1;
        }

        @Override
        public int getItemViewType(int position) {
            //在第一个位置添加头
            if (position==0){
                return TYPE_HEADER;
            }
            return super.getItemViewType(position);
        }



    }

}


